package com.ruoyi.web.controller.system;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import com.ruoyi.common.core.domain.entity.SysModule;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.system.service.ISysModuleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysMenu;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.service.ISysMenuService;

import static com.ruoyi.common.constant.CacheConstants.DEFAULT_MODULE_KEY;

/**
 * 菜单信息
 *
 * @author ruoyi
 */
@RestController
@RequestMapping("/system/menu")
public class SysMenuController extends BaseController
{
    @Autowired
    private ISysMenuService menuService;

    @Autowired
    private ISysModuleService moduleService;

    @Autowired
    private RedisCache redisCache;

    /**
     * 获取菜单列表
     */
    @PreAuthorize("@ss.hasPermi('system:menu:list')")
    @GetMapping("/list")
    public AjaxResult list(SysMenu menu)
    {
        List<SysMenu> menus = menuService.selectMenuList(menu, getUserId());
        return success(menus);
    }

    /**
     * 根据菜单编号获取详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:menu:query')")
    @GetMapping(value = "/{menuId}")
    public AjaxResult getInfo(@PathVariable Long menuId)
    {
        SysMenu menu = menuService.selectMenuById(menuId);
        if (menu != null) {
            SysModule defaultModule = moduleService.getDefaultModuleByModuleName(menu.getMenuName());
            if (defaultModule != null) {
                menu.getParams().put("defaultDataPermission", defaultModule.getDataScope());
            }
        }
        return success(menu);
    }

    /**
     * 获取菜单下拉树列表
     */
    @GetMapping("/treeselect")
    public AjaxResult treeselect(SysMenu menu)
    {
        List<SysMenu> menus = menuService.selectMenuList(menu, getUserId());
        return success(menuService.buildMenuTreeSelect(menus));
    }

    /**
     * 加载对应角色菜单列表树
     */
    @GetMapping(value = "/roleMenuTreeselect/{roleId}")
    public AjaxResult roleMenuTreeselect(@PathVariable("roleId") Long roleId)
    {
        List<SysMenu> menus = menuService.selectMenuList(getUserId());
        AjaxResult ajax = AjaxResult.success();
        ajax.put("checkedKeys", menuService.selectMenuListByRoleId(roleId));
        ajax.put("menus", menuService.buildMenuTreeSelect(menus));
        return ajax;
    }

    /**
     * 新增菜单
     */
    @PreAuthorize("@ss.hasPermi('system:menu:add')")
    @Log(title = "菜单管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody SysMenu menu, @RequestParam Integer defaultDataPermission)
    {
        if (!menuService.checkMenuNameUnique(menu))
        {
            return error("新增菜单'" + menu.getMenuName() + "'失败，菜单名称已存在");
        }
        else if (UserConstants.YES_FRAME.equals(menu.getIsFrame()) && !StringUtils.ishttp(menu.getPath()))
        {
            return error("新增菜单'" + menu.getMenuName() + "'失败，地址必须以http(s)://开头");
        }
        menu.setCreateBy(getUsername());
        int result = menuService.insertMenu(menu);
        if (defaultDataPermission != 0){
            generateDefaultDataPermission(menu, defaultDataPermission);
        }
        return toAjax(result);
    }

    /**
     * 修改菜单
     */
    @PreAuthorize("@ss.hasPermi('system:menu:edit')")
    @Log(title = "菜单管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody SysMenu menu, @RequestParam Integer defaultDataPermission)
    {
        if (!menuService.checkMenuNameUnique(menu))
        {
            return error("修改菜单'" + menu.getMenuName() + "'失败，菜单名称已存在");
        }
        else if (UserConstants.YES_FRAME.equals(menu.getIsFrame()) && !StringUtils.ishttp(menu.getPath()))
        {
            return error("修改菜单'" + menu.getMenuName() + "'失败，地址必须以http(s)://开头");
        }
        else if (menu.getMenuId().equals(menu.getParentId()))
        {
            return error("修改菜单'" + menu.getMenuName() + "'失败，上级菜单不能选择自己");
        }
        menu.setUpdateBy(getUsername());
        SysModule defaultModule = moduleService.getDefaultModuleByModuleName(menu.getMenuName());
        if (defaultDataPermission != 0){
            if (defaultModule != null){
                defaultModule.setDataScope(defaultDataPermission);
                moduleService.updateModule(defaultModule);
            } else {
                generateDefaultDataPermission(menu, defaultDataPermission);
            }
        } else {
            if (defaultModule != null) {
                moduleService.deleteModuleById(defaultModule.getModuleId());
            }
        }
        return toAjax(menuService.updateMenu(menu));
    }

    private void generateDefaultDataPermission(SysMenu menu, Integer defaultDataPermission) {
        SysModule newDefaultModule = new SysModule();
        String perms = menu.getPerms();
        String tableName = extractTableName(perms);
        newDefaultModule.setTableName(tableName);
        newDefaultModule.setModuleName(menu.getMenuName());
        newDefaultModule.setRoleId(0L);
        newDefaultModule.setRoleName("默认权限");
        newDefaultModule.setDataScope(defaultDataPermission);
        newDefaultModule.setCreateBy(getUsername());
        moduleService.insertModule(newDefaultModule);
        Set<String> tableNames = new HashSet<>();
        tableNames.add(tableName);
        redisCache.setCacheSet(DEFAULT_MODULE_KEY,tableNames);
    }

    private String extractTableName(String perms) {
        if (perms == null || !perms.contains(":")) {
            return perms;
        }
        String[] parts = perms.split(":");
        if (parts.length >= 2) {
            String module = parts[0];
            String entity = parts[1];
            // Convert system to sys, keep other modules as is
            if ("system".equals(module)) {
                module = "sys";
            }
            return module + "_" + entity;
        }
        return perms.replace(":", "_");
    }

    /**
     * 删除菜单
     */
    @PreAuthorize("@ss.hasPermi('system:menu:remove')")
    @Log(title = "菜单管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{menuId}")
    public AjaxResult remove(@PathVariable("menuId") Long menuId)
    {
        if (menuService.hasChildByMenuId(menuId))
        {
            return warn("存在子菜单,不允许删除");
        }
        if (menuService.checkMenuExistRole(menuId))
        {
            return warn("菜单已分配,不允许删除");
        }
        SysMenu menu = menuService.selectMenuById(menuId);
        SysModule defaultModule = moduleService.getDefaultModuleByModuleName(menu.getMenuName());
        if (defaultModule != null) {
            moduleService.deleteModuleById(defaultModule.getModuleId());
        }
        return toAjax(menuService.deleteMenuById(menuId));
    }
}